package com.skydoves.chatgpt.feature.chat.ddd.bots

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import com.example.core_database.entities.Bot
import com.skydoves.chatgpt.core.designsystem.composition.LocalOnFinishDispatcher
import com.skydoves.chatgpt.core.navigation.AppComposeNavigator
import com.skydoves.chatgpt.core.navigation.ChatGPTScreens
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone


@Composable
fun BotsChannels(
  modifier: Modifier,
  composeNavigator: AppComposeNavigator,
  onFinishDispatcher: (() -> Unit)? = LocalOnFinishDispatcher.current,
) {

  //背景图片
  AsyncImage(
    model = "https://img.picui.cn/free/2024/11/12/67332a12c8625.jpg",
    null,
    modifier = Modifier.fillMaxSize(),
  )

  BotsScreens(
    modifier = modifier,
    composeNavigator = composeNavigator,
    onBackPressed = { onFinishDispatcher?.invoke() }
  )
}


@SuppressLint("SuspiciousIndentation")
@Composable
fun BotsScreens(
  modifier: Modifier,
  viewModel: BotsViewModel = hiltViewModel(),
  composeNavigator: AppComposeNavigator,
  onBackPressed: () -> Unit = {},
) {
  // 观察 ViewModel 中的 allBots 数据
  val botsList by viewModel.allBots.observeAsState(emptyList())
  val Uid = viewModel.Uid
  val filteredBots = botsList.filter { bot -> bot.userId == Uid }
  // 展示 bot 列表
  LazyColumn(
    modifier = modifier
      .fillMaxWidth()
      .background(color = Color.White.copy(alpha = 0.6f))
  ) {
    items(filteredBots) { bot ->
      BotItem(
        bot = bot,
        onClick = {
          Log.i("Route",ChatGPTScreens.Messages.createRoute(bot))
          composeNavigator.navigate(ChatGPTScreens.Messages.createRoute(bot))
        }
      )
    }
  }
}

fun timestampToTime(timestamp: Long): String {
  val adjustedTimestamp = if (timestamp.toString().length == 10) timestamp * 1000 else timestamp
  val date = Date(adjustedTimestamp)
  val format = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
  format.timeZone = TimeZone.getTimeZone("Asia/Shanghai") // 设置为北京时间（上海）
  return format.format(date)
}

@Composable
fun BotItem(
  bot: Bot,
  onClick: () -> Unit,
) {
  val time = timestampToTime(bot.lastMessageTime)

  Column(
    modifier = Modifier
      .fillMaxWidth()
      .padding(1.dp)
      .clickable(onClick = onClick)
  ) {
    Spacer(modifier = Modifier.height(8.dp))
    Row {
      Spacer(modifier = Modifier.width(10.dp))
      AsyncImage(
        model = bot.head,
        null,
        contentScale = ContentScale.Crop,
        modifier = Modifier
          .size(50.dp)
          .clip(CircleShape),
        )
      Spacer(modifier = Modifier.width(15.dp))
      Column {
        Text(
          text = bot.botName,
          style = MaterialTheme.typography.titleLarge
        )
        Row {
          Text(
            text = bot.lastMessageContent,
            maxLines = 1, overflow = TextOverflow. Ellipsis,
            modifier = Modifier.weight(0.6f)
          )
          Box(
            modifier = Modifier
              .fillMaxWidth()
              .weight(0.4f),
            contentAlignment = Alignment.CenterEnd
          ) {
            Text(
              text = time,
              )
          }
        }
      }
    }
    Spacer(modifier = Modifier.height(8.dp))
  }
}


